package cn.news.upload.action;

import java.sql.Timestamp;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartRequest;

import cn.news.upload.entities.OperResult;
import cn.news.upload.entities.XhUploadInfo;
import cn.news.upload.service.InfoService;
import cn.news.upload.service.UploadService;
import cn.news.upload.utils.JasonUtils;

@Controller
@RequestMapping(value = "/file")
public class FileUploadAction {
	private Logger logger = LoggerFactory.getLogger(FileUploadAction.class);
	@Autowired
	private UploadService sv;
	@Autowired
	private InfoService infosv;

	@RequestMapping(value = "upload")
	public String upload(XhUploadInfo info, @RequestParam String v1, @RequestParam String v2, HttpServletRequest request,
			HttpServletResponse response) {
		logger.debug("[file add] start");
		String referer = request.getHeader("referer");
		OperResult or = new OperResult();
		
		if(null == info){
			or.setCode(OperResult.CODE_FAIL);
			or.setMessage("info is null");
			JasonUtils.writeJasonP(request, response, or);
			return "redirect:" + v2;
		}
		
		info.setCreateTime(new Timestamp(System.currentTimeMillis()));

		try {
			OperResult orc = infosv.checkApp(info, referer);
			if (orc.getCode() == OperResult.CODE_FAIL) {
				JasonUtils.writeJasonP(request, response, orc);
				return "redirect:" + v2;
			}

			MultipartRequest multiRequest = (MultipartRequest) request;
			List<MultipartFile> fileList = multiRequest.getFiles("uploadfile");
			sv.uploadInfo(fileList, info);

			infosv.addInfo(info);
		} catch (Exception e) {
			logger.error("[file add] exception : " + e.getMessage(), e);
			or.setCode(OperResult.CODE_FAIL);
			or.setMessage(e.getMessage());
			return "redirect:" + v2;
		}

		logger.debug("[file add] finish, result=" + or);
		JasonUtils.writeJasonP(request, response, or);
		return "redirect:" + v1;
	}
}